package utlis;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DaoUtils {

    public static int commonsUpdate(String sql, Object... args) throws SQLException {
        Connection connection = JDBCUtils.getConnection();
        PreparedStatement prepareStatement = connection.prepareStatement(sql);
        if (args != null){
            for (int i = 0; i < args.length; i++) {
                prepareStatement.setObject(i+1,args[i]);
            }
        }
        int count = prepareStatement.executeUpdate();
        //关闭资源
        prepareStatement.close();
        return count;

    }

    public static <T> List<T> commonsQuery(String sql,Class c,Object... args) throws SQLException {
        Connection connection = JDBCUtils.getConnection();
        PreparedStatement prepareStatement = connection.prepareStatement(sql);
        if (args != null){
            for (int i = 0; i < args.length; i++) {
                prepareStatement.setObject(i+1,args[i]);
            }
        }
        ResultSet resultSet = prepareStatement.executeQuery();
        List<T> list = new ArrayList<>();
        while (resultSet.next()){
            //获取该类的对象的所有属性
            Field[] declaredFields = c.getDeclaredFields();
            try {
                //创建一个该类的对象
                T obj = (T) c.getConstructor().newInstance();
                for (int i = 0; i < declaredFields.length; i++) {
                    //获取属性名
                    String name = declaredFields[i].getName();
                    //调用属性名的set方法
                    Method method = c.getMethod("set" + name.substring(0, 1).toUpperCase() + name.substring(1), declaredFields[i].getType());
                    //调用set方法给属性赋值
                    method.invoke(obj,resultSet.getObject(i+1));
                }
                //将该对象添加到集合中
                list.add(obj);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        //关闭资源
        prepareStatement.close();
        resultSet.close();

        return list;
    }
}
